package com.wodogs.recharge.battlenet;

import java.util.List;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.springframework.stereotype.Component;

import com.wd.core.spring.support.SpringUtils;
import com.wodogs.recharge.BaseService;
import com.wodogs.recharge.entity.UserAccount;
import com.wodogs.utils.AppException;
import com.wodogs.utils.BaseManage;
import com.wodogs.utils.tools.LogFile;

@Component
public class BattlenetManage extends BaseManage{
	
	private final static Log logger = LogFactory.getLog(BaseManage.class);  
	
	public static String WEB_SITE = "battlenet";
	
	public static String LOGIN_URL = "https://www.battlenet.com.cn/login/zh/?ref=https://www.battlenet.com.cn/account/management/ebalance-purchase.html&app=bam&cr=true";
	
//	public static String RECHARGE_URL = "https://www.battlenet.com.cn/account/management/ebalance-purchase.html";

//	@Autowired
	private BaseService service;
	
	//输入卡密页面
	//卡号
	public static String cardNo_id = "cardNo";
	//卡密
	public static String cardPin_id= "cardPin";
	
	//成功的标签
	public static String successXpath = "//*[@class='alert-page-message success-page']";
	//失败标签
	public static String failXpath = "//*[@class='alert-message']";
	//充值按钮
	public static String btn_id = "redeem-code";
	
	//安全码页面
	//安全码输入框
	public static String auth_id = "authValue";
	//安全码提交按钮
	public static String btnSubmit_id = "submit";
	
	public BattlenetManage(){
		super();
		//账号
		//input[@id="accountName"]
		this.loginNameXpath = "//*[@id='accountName']";
		//密码
		//input[@id="password"]
		this.loginPwdXpath = "//*[@id='password']";
		//登录按钮
//		//button[@id="submit"]
		this.loginBtnXpath = "//*[@id='submit']";
		//用户名 
		this.usernameXpath = "//*[@class='nav-link username needsclick dropdown-toggle']";
		
		service = (BaseService) SpringUtils.getBean("baseService");
		
	}
	
	public void loginAndRecharge(List<UserAccount> accountList) throws InterruptedException{
		if(accountList == null || accountList.size()<1){
			return;
		}
		//初始化并且登陆
		boolean login_success = login(accountList);
		//如果登陆失败直接返回
		if(!login_success){
			return;
		}
		//充值
		try{
			rechage(accountList);
		}catch(Exception ex){
			logger.error(ex.getMessage());
		}finally {
			try{
				driver.close();
			}catch(Exception ex){}
		}
	}
	
	private void storeCaptche(List<UserAccount> accountList){
		WebElement captchaElement = null;
		try{
			captchaElement = driver.findElement(By.cssSelector("div.captcha-image>img"));
			if(captchaElement == null){
				return;
			}
			String fileName = UUID.randomUUID().toString().replace("-", "");
			snapshotElement(driver, captchaElement, WEB_SITE, fileName);
			service.updateCaptchaPic(accountList, fileName+".png");
			
		}catch(Exception ex){
			return;
		}
//		//等三分钟，检测是否拖动极验成功
//        (new WebDriverWait(driver, 180)).until(new ExpectedCondition<Boolean>() {  
//        	public Boolean apply(WebDriver d) {  
////		//div[@class='gt_slider']/div[@class='gt_ajax_tip success']
////		WebElement e = d.findElement(By.xpath("//div[@class='gt_slider']/div[@class='gt_ajax_tip success']"));
////		return e!=null; 
//        		 WebElement e = d.findElement(By.xpath("//div[@class='gt_slider']/div[@class='gt_ajax_tip success']"));
//        		 return e!=null;
//        	}
//        });
	}
	
	
	public boolean login(List<UserAccount> accountList) throws InterruptedException{
		if(accountList == null || accountList.size()<1){
			return false;
		}
		try{
			initPhantomJSDriver();
			//加载页面登陆
			initPage(accountList.get(0).getLogin_url());
			// 获取 网页的 title  
			logger.info("1 Page title is: " + driver.getTitle());
	        
			//保存验证码
			storeCaptche(accountList);
			
	        //输入账号密码并登录
	        doLogin(accountList.get(0));
	        
	        // 显示搜索结果页面的 title  
	        logger.info("2 Page title is: " + driver.getTitle());
		}catch(AppException ex){
			logger.error(ex.getMessage());
			logger.error(getBodyHtml());
			if(ex.type != null){
				service.update(accountList,ex.type,ex.getMessage());
			}else{
				service.update(accountList,5,ex.getMessage());
			}
			return false;
		}catch(Throwable ex){
			logger.error(ex.getMessage());
			ex.printStackTrace();
			logger.error(getBodyHtml());
			service.update(accountList,5,ex.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 充值某个账号的多个卡密
	 * @param accountList
	 * @throws InterruptedException
	 */
	private void rechage(List<UserAccount> accountList) throws InterruptedException{
		if(accountList == null){
			return;
		}
		for(UserAccount account:accountList){
			try{
				boolean is_ok = rechage(account);
				if(is_ok){
					service.update(accountList,1,"充值成功");
				}else{
					service.update(accountList,4,"其他不明原因的失败");
				}
			}catch(AppException ex){
				logger.error(ex.getMessage());
				logger.error(getBodyHtml());
				if(ex.type != null){
					service.update(account.getId(),ex.type,ex.getMessage());
				}else{
					service.updateFail(account.getId(),ex.getMessage());
				}
			}catch(Throwable ex){
				logger.error(ex.getMessage());
				logger.error(getBodyHtml());
				service.updateAccountErr(account.getId(),ex.getMessage());
			}
		}
	}
	
	/**
	 * 按单个账号充值
	 * @param account
	 * @return
	 * @throws InterruptedException
	 */
	private boolean rechage(UserAccount account) throws InterruptedException{
		if(account == null || StringUtils.isBlank(account.getCardNo()) || StringUtils.isBlank(account.getCardPin())){
			throw new AppException(3,"卡密或者url中有空值哇");
		}
		//开始充值
		System.out.println("开始充值 " + driver.getTitle());
		
		String cardNo = account.getCardNo();
		String cardPin = account.getCardPin();
		
		String url = account.getUrl();
		if(StringUtils.isNotBlank(url)){
			try {
				initPage(url);
			} catch (InterruptedException e) {
				throw new AppException(e.getMessage());
			}
		}
		
		(new WebDriverWait(driver, 5)).until(new ExpectedCondition<Boolean>() {  
			public Boolean apply(WebDriver d) {  
				try{
					WebElement e = d.findElement(By.id(cardNo_id));
					return e!=null;
				}catch(Exception ex){
					return false;
				}
			}
		});
		LogFile logFile = new LogFile(WEB_SITE,cardNo);
		logFile.append("卡号:"+cardNo);
		logFile.append(getBodyHtml());
		
		//卡号
		WebElement cardNoEle = driver.findElement(By.id(cardNo_id));  
		cardNoEle.sendKeys(cardNo); // 输入关键字  
		
		//密码
        WebElement cardPinEle = driver.findElement(By.id(cardPin_id));  
        cardPinEle.sendKeys(cardPin);  // 输入关键字  
        logger.info("检测兑换按钮" + driver.getTitle());
        try{
        	//兑换按钮
        	(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {  
        		public Boolean apply(WebDriver d) {  
        			boolean a = false;
        			try{
        				WebElement btn = getDuihuanBtn();
        				return btn.isEnabled();
        			}catch(Exception ex){
        				return a;
        			}
        		}
        	});
        }catch(Exception ex){
        	throw new AppException(3,"兑换按钮点不了哇，看看卡密位数是否有误，战网密码要9位!");
        }
        //点击兑换
        logger.info("点击兑换" + driver.getTitle());
        WebElement btn = getDuihuanBtn();
        btn.click();
        Thread.sleep(500);
//      战网点数充值成功。如果错误的部分抓不到，就说明成功了
        logger.info("错误的部分抓取" + driver.getTitle());
        logFile.append(getBodyHtml());
        WebElement fail = null;
        try{
        	fail = driver.findElement(By.xpath(failXpath));
        	logger.error(fail.getAttribute("outerHTML"));
        }catch(Exception ex){
        	return true;
        }
        String msg = fail.getAttribute("outerHTML");
        
        if(msg.indexOf("尝试次数过多，请过一段时间后重试。")>-1){
        	throw new AppException(4, msg);
        }
        if(msg.indexOf("无效的卡号或密码")>-1){
        	throw new AppException(3, msg);
        }
        throw new AppException(3, msg);
        
	}

	@Override
	protected void inputTestAfterClicke(UserAccount account){
		final String eCode = account.getEcode();
		try {
			Thread.sleep(500);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		//等15秒，看输入安全口令的页面会不会出来.如果出来，说明已经到了输入安全码的地方
		(new WebDriverWait(driver, 20)).until(new ExpectedCondition<Boolean>() {  
			public Boolean apply(WebDriver d) {  
				try{
					//检测卡号的输入框是否存在，如果存在就不需要输入安全码，直接跳转
					WebElement cardNoInput = driver.findElement(By.id(cardNo_id));
					if(cardNoInput != null){
						return true;
					}
				}catch(Exception ex){
				}
				try{
					WebElement authValueInput = d.findElement(By.id(auth_id));
					//如果安全码的输入框也不存在，就返回继续检测
					if(authValueInput == null){
						return false;
					}
					//如果安全码存在。就输入安全码并确认
					inputAuthCode(eCode);
					return true;
				}catch(Exception ex){
					logger.error(getBodyHtml());
					return false;
				}
			}
		});
	}
	
	@Override
	protected void doLoginSetNamePwd(String loginName,String password){
		// 通过 id 找到 input 的 DOM  
        WebElement uid = driver.findElement(By.xpath(loginNameXpath));  
        uid.sendKeys(loginName); // 输入关键字  
        
        // 通过 id 找到 input 的 DOM  
        WebElement passwd = driver.findElement(By.xpath(loginPwdXpath));  
        passwd.sendKeys(password);  // 输入关键字  
	}
	
	

	private void inputAuthCode(String eCode) {
		// 输入安全口令
		WebElement authValueEle = driver.findElement(By.id(auth_id));
		authValueEle.sendKeys(eCode); // 输入关键字

		WebElement btnEle = driver.findElement(By.id(btnSubmit_id));
		btnEle.click();
	}
	
	private String getBodyHtml(){
		return driver.findElement(By.cssSelector("body")).getAttribute("outerHTML");
	}
	
//	private void getErrMsg(String str){
//		try{
//			WebElement fail = driver.findElement(By.xpath(failXpath));
//			if(fail != null){
//				String msg = fail.getAttribute("outerHTML");
//				
//				if(msg.indexOf("尝试次数过多，请过一段时间后重试。")>-1){
//					throw new AppException(4, msg);
//				}
//				throw new AppException(3, msg);
//			}
//			throw new AppException(str);
//		}catch(Exception ex){
//			throw new AppException(4, ex.getMessage());
//		}
//	}
	
//	public void login(UserAccount account) throws InterruptedException{
//		if(account == null || StringUtils.isBlank(account.getAccount()) || StringUtils.isBlank(account.getPassword())
//				|| StringUtils.isBlank(account.getCardNo()) || StringUtils.isBlank(account.getCardPin())
//				|| StringUtils.isBlank(account.getLogin_url()) || StringUtils.isBlank(account.getUrl())){
//			return;
//		}
//		try{
//			//初始化浏览器
////			initDriver(null);
//			initPhantomJSDriver();
//			//加载页面
//			initPage(account.getLogin_url());
//			// 获取 网页的 title  
//			logger.info("1 Page title is: " + driver.getTitle());
////			System.out.println("1 Page title is: " + driver.getTitle());
//	        
//	        //输入账号密码并登录
//	        doLogin(account);
//	        
//	        // 显示搜索结果页面的 title  
//	        logger.info("2 Page title is: " + driver.getTitle());
////	        System.out.println("2 Page title is: " + driver.getTitle());
////	        //关闭浏览器  
//	        boolean is_ok = rechage(account);
//	        if(is_ok){
//	        	service.update(account.getId(),1,"充值成功");
//	        }else{
//	        	service.update(account.getId(),4,"其他不明原因的失败");
//	        }
//	        return;
//		}catch(AppException ex){
//			logger.error(ex.getMessage());
//			if(ex.type != null){
//				service.update(account.getId(),ex.type,ex.getMessage());
//			}else{
//				service.updateFail(account.getId(),ex.getMessage());
//			}
//			logger.error(getBodyHtml());
//		}catch(Exception ex){
//			logger.error(ex.getMessage());
//			service.updateAccountErr(account.getId(),ex.getMessage());
//			logger.error(getBodyHtml());
//		}catch(Throwable ex){
//			logger.error(ex.getMessage());
//			service.updateAccountErr(account.getId(),ex.getMessage());
//			ex.printStackTrace();
//			logger.error(getBodyHtml());
//		}finally{
//			driver.close();
//		}
//		return;
//	}
	
	private WebElement getDuihuanBtn(){
		//兑换按钮
        WebElement btn = driver.findElement(By.id(btn_id)); 
        return btn;
	}
	
}
